import { useMemo, useEffect, useState, useRef, useLayoutEffect } from "react";
import {  getAllType ,addType ,delType,editType }  from '../../api/roomType'
import Com from '../../components/common'
import './style.scss'
import {
    Button,
    Table,
    Drawer,
    Space,
    Form,
    Input,
    InputNumber,
    message,
    Modal,
    Row,
    Col
} from "antd";

const RoomSafe = () => {

    const columns = useMemo(()=>[
        {title: '房型',dataIndex: 'name',key:'name'},
        {
            title: '简称',
            dataIndex: 'shortName',
            key: 'shortName',
            render: (_, record) => {
                return record.shortName || "无"
            }
        },
        {title: '门市价',dataIndex: 'price',key:'price'},
        {
            title: '押金',
            dataIndex: 'yaPrice',
            key: 'yaPrice',
            render: (_, record) => {
                return record.yaPrice || "无"
            }
        },
        {title: '床位数',dataIndex: 'beds',key:'beds'},
        {title: '可住人数',dataIndex: 'liveLimit',key:'liveLimit'},
        {title: '早餐卷量',dataIndex: 'couponNum',key:'couponNum'},
        {
            title: '操作', dataIndex: '_id',key:'_id',
            render:(_, record)=>{ 
                return <> 
                            <Button  variant="outline" size="small" onClick={()=>confirm(record)}>删除</Button> 
                            <Button variant="outline" style={{ marginLeft: '5px' }} size="small" onClick={()=>Edit(record)}>修改</Button> 
                        </>
            }
        },
    ], [])

    // 请示删除
    const confirm = (val) => {
        Modal.confirm({
          title: '删除',
          content: '确定删除吗??',
          okText: '确认',
            cancelText: '取消',
            onOk(){confirmDel(val)}
        });
      };

    //删除
    const confirmDel = async(value) => {
        let res = await delType({typeid:value._id});
        const  {success} = res;
        if(!success) return  message.error('删除失败');
        message.success('删除成功');
        getData();
    }



    //显示抽屉
    const [visible, setVisible] = useState(false);
    const showDrawer = () => {
        setVisible(true);
      };
    const onClose = () => {
        setVisible(false);
    };
    //添加房型
    const [addRef] = Form.useForm()
    const onFinish = async (value) => {
        let res = await addType(value);
        const { success } = res;
        if (!success) return   message.error('添加失败');
        message.success('添加成功');
        getData()
        addRef.setFieldsValue(
            {
                name: '',
                shortName:'',
                liveLimit: 1,
                beds: 1,
                couponNum: 0,
                price: '',
                yaPrice:''
            }
        )
        setVisible(false);
    }

    const [data,setData] = useState([]);
    const [limit,setLimit] = useState(10);
    const [page,setPage] = useState(1); 
    const [total ,setTotal] = useState(0);

    const getData = async ()=>{
        const postData = { limit,page };
        let res = await getAllType(postData)
        const { success, data, count } = res;
        const a = []  
        for (let item of data) {
            item.key = item._id
            a.push(item)
        }
        if(success) {
            setData(a);
            setTotal(count)
        };   
    }

    const changepage = (page,limit) => {
        setPage(page);
        setLimit(limit)
    }

    useLayoutEffect(()=>{
        getData();
    }, [limit, page])
    

    const [roomedit, setRoomedit] = useState(false);
    const [editRef] = Form.useForm()

    const onroomClose = () => {
        setRoomedit(false)
    }

    const Edit = value => {
        value.key = value._id
        editRef.setFieldsValue(value)
        setRoomedit(true)
    }

    const editroon = async () => {
        let data = editRef.getFieldsValue()
        let res = await editType({
            ...data,
            typeid:data._id
        });
        const { success } = res;
        if (!success) return   message.error('修改失败');
        message.success('修改成功');
        getData()
        editRef.setFieldsValue(
            {
                name: '',
                shortName:'',
                liveLimit: 1,
                beds: 1,
                couponNum: 0,
                price: '',
                yaPrice:''
            }
        )
        setRoomedit(false)
    }
    // 搜索功能
    const [inputValue, setInputValue] = useState('')
    
    const search = async() => {
        const postData = { limit, page ,name:inputValue};     
        let res = await getAllType(postData)
        const { success, data, count } = res;
        const a = []  
        for (let item of data) {
            item.key = item._id
            a.push(item)
        }
        if(success) {
            setData(a);
            setTotal(count)
        };   
    }


    return (
        <Com title="房型维护">
            <Row >
                <Col span={6}>  
                    <Button type="primary" onClick={showDrawer}>添加新的房型</Button>   
                </Col>
                <Col span={4}></Col>
                <Col span={6}>
                    <Input
                        placeholder="请输入要搜索的房型"
                        value={inputValue}
                        onChange={ (e)=>setInputValue(e.target.value)}
                    />
                </Col>
                <Col span={1}></Col>
                <Col span={7}>
                    <Button type="primary" onClick={search}>搜索</Button>
                </Col>
            </Row>
            <div>
                <Table
                    columns={columns}
                    dataSource={data}
                    pagination={
                        {
                            defaultPageSize: limit,
                            defaultCurrent:page,
                            total: total,
                            current:page,
                            onChange:changepage
                        }
                    }
                />
            </div>
            <Drawer
                title="房型的添加"
                placement="right"
                width={500}
                onClose={onClose}
                visible={visible}
                closable={false}      
            >
                <Form
                    labelCol={{ span: 5, }}
                    wrapperCol={{ span: 15, }}
                    layout="horizontal"
                    initialValues={{
                        name: '',
                        shortName:'',
                        liveLimit: 1,
                        beds: 1,
                        couponNum: 0,
                        price: '',
                        yaPrice:''
                    }}   
                    onFinish={onFinish}
                    form={ addRef }
                >
                    <Form.Item
                        label="房型名称"
                        name="name"
                        rules={[
                          {
                            required: true,
                            message: '房型名称不能为空!',
                          },
                        ]}
                    >
                        <Input placeholder="请输入房型名称"/>
                    </Form.Item>
                    <Form.Item
                        label="简称"
                        name="shortName"
                    >
                        <Input placeholder="请输入房型简称"/>
                    </Form.Item>
                    <Form.Item label="入住人数" name="liveLimit">
                        <InputNumber
                            min={1}
                            max={10}
                            step={1}
                        />
                    </Form.Item>
                    <Form.Item label="床数" name="beds">
                        <InputNumber
                            min={1}
                            max={10}
                            step={1}
                        />
                    </Form.Item>
                    <Form.Item
                        label="价格"
                        name="price"
                        rules={[
                          {
                            required: true,
                            message: '价格不能为空!',
                          },
                        ]}
                    >
                        <Input placeholder="请输入押金"/>
                    </Form.Item>
                    <Form.Item
                        label="押金"
                        name="yaPrice"
                    >
                        <Input placeholder="请输入押金"/>
                    </Form.Item>
                    <Form.Item label="早餐卷数量" name="couponNum">
                        <InputNumber
                            min={0}
                            max={10}
                            step={1}
                        />
                    </Form.Item>
                    <Form.Item >
                        <Button type="primary" onClick={onClose}>取消</Button>
                        <Button type="primary" htmlType="submit">立即添加</Button>
                    </Form.Item>
                </Form>
            </Drawer>
        
            <Drawer
                title="房型的修改"
                placement="right"
                width={500}
                onClose={onroomClose}
                visible={roomedit}
                closable={false}
            >
                <Form
                    labelCol={{ span: 5, }}
                    wrapperCol={{ span: 15, }}
                    layout="horizontal"
                    initialValues={{
                        name: '',
                        shortName:'',
                        liveLimit: 1,
                        beds: 1,
                        couponNum: 0,
                        price: '',
                        yaPrice:''
                    }}   
                    onFinish={onFinish}
                    form={ editRef }
                >
                    <Form.Item
                        label="房型名称"
                        name="name"
                        rules={[
                          {
                            required: true,
                            message: '房型名称不能为空!',
                          },
                        ]}
                    >
                        <Input placeholder="请输入房型名称"/>
                    </Form.Item>
                    <Form.Item
                        label="简称"
                        name="shortName"
                    >
                        <Input placeholder="请输入房型简称"/>
                    </Form.Item>
                    <Form.Item label="入住人数" name="liveLimit">
                        <InputNumber
                            min={1}
                            max={10}
                            step={1}
                        />
                    </Form.Item>
                    <Form.Item label="床数" name="beds">
                        <InputNumber
                            min={1}
                            max={10}
                            step={1}
                        />
                    </Form.Item>
                    <Form.Item
                        label="价格"
                        name="price"
                        rules={[
                          {
                            required: true,
                            message: '价格不能为空!',
                          },
                        ]}
                    >
                        <Input placeholder="请输入押金"/>
                    </Form.Item>
                    <Form.Item
                        label="押金"
                        name="yaPrice"
                    >
                        <Input placeholder="请输入押金"/>
                    </Form.Item>
                    <Form.Item label="早餐卷数量" name="couponNum">
                        <InputNumber
                            min={0}
                            max={10}
                            step={1}
                        />
                    </Form.Item>
                    <Form.Item  name="_id">
                        <Button type="primary" onClick={onroomClose}>取消</Button>
                        <Button type="primary" onClick={editroon}>立即修改</Button>
                    </Form.Item>

                </Form>
            </Drawer>
        
        </Com>
    )
}

export default RoomSafe